//
//  HKSecureViewController.m
//  AQBPolice
//
//  Created by apple on 2017/7/5.
//  Copyright © 2017年 eight. All rights reserved.
//

#import "HKSecureViewController.h"
#import "HKGoPoliceViewController.h"
#import "HKAssignPoliceViewController.h"
#import "ReachabilityTool.h"
#import <UserNotifications/UserNotifications.h>

#import "HMAudioTool.h"
#import <AVFoundation/AVFoundation.h>

@interface HKSecureViewController ()<BMKMapViewDelegate,BMKLocationServiceDelegate,BMKGeoCodeSearchDelegate,UNUserNotificationCenterDelegate>


@property (nonatomic, strong) BMKLocationService *locService;//定位
@property (nonatomic, strong) BMKMapView *mapView;//地图
//用于产生动画的imageView
@property (weak, nonatomic) IBOutlet UIImageView *animImage;
//管理动画的timer
@property (nonatomic, strong) NSTimer *animTimer;

/**
 出警按钮
 */
@property (weak, nonatomic) IBOutlet UIButton *goPoliceButton;

/**
 收工按钮
 */
@property (weak, nonatomic) IBOutlet UIButton *goHomeButtom;

/**
 动画对象
 */
@property (nonatomic, strong) CABasicAnimation *animation;

/**
 接警详情界面
 */
@property (nonatomic, strong) HKGoPoliceViewController *goVC;

/**
 派给其他警员界面
 */
@property (nonatomic, strong) HKAssignPoliceViewController *assignVC;

/**
 倒计时的计数器
 */
@property (nonatomic, assign) int count;

/**
 倒计时的timer对象
 */
@property (nonatomic, strong) NSTimer *countTimer;

/**
 轮询警情timer
 */
@property (nonatomic, strong) NSTimer *alarmTimer;

@end

@implementation HKSecureViewController


#pragma mark - view生命周期
- (void)viewWillDisappear:(BOOL)animated {
    [self.mapView viewWillDisappear];
    self.mapView.delegate = nil; // 不用时，置nil
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    
    [self.mapView viewWillAppear];
    self.mapView.delegate = self; // 此处记得不用的时候需要置nil，否则影响内存的释放
    //状态栏黑色
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    HKLog(@"%@", NSStringFromCGRect(self.goPoliceButton.frame));
    
    
    [ReachabilityTool getReachability];
    
    //新功能，获取崩溃之前的状态
    [self getCrashStateWithPoliceId:policeNumber];
    
    [MBProgressHUD showSuccess:@"登录成功" toView:self.view.window];
    
    //不能接警通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(canNotGoPolice) name:@"CanNotGoPoliceNotification" object:nil];
    //已经处理警情通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didDisposePolice) name:@"didDisposePoliceNotification" object:nil];
    //已经处理警情通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(goHomeButtonEnable) name:@"goHomeButtonNotification" object:nil];
    
    //发送通知，安全宝界面结束倒计时的Timer，取消听警
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didGoPolice) name:@"didGoPoliceNotification" object:nil];
    
    
    [self.goPoliceButton setTitle:@"出警" forState:UIControlStateNormal];
    [self.goPoliceButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.goPoliceButton setBackgroundImage:[UIImage imageNamed:@"D44FB0CD-23DB-4B0B-842A-987F59080059.png"] forState:UIControlStateNormal];
    //隐藏收工按钮
    self.goHomeButtom.hidden = YES;
    //背景颜色
    self.view.backgroundColor = HKColor(100, 107, 140);
    [self startLocation];
}

#pragma mark - 通知
- (void)canNotGoPolice {
    //隐藏接警详情界面,并且弹出派给其他警员界面
    [self.goVC.view removeFromSuperview];
    [self.goVC removeFromParentViewController];
    
    self.assignVC = [[HKAssignPoliceViewController alloc] initWithNibName:@"HKAssignPoliceViewController" bundle:nil];
    if (kScreen_width == 320) {//5,5s,5SE
        self.assignVC.view.frame = CGRectMake((kScreen_width-240)/2, 80, 240, 300);
    }else {//6,6s,7
        self.assignVC.view.frame = CGRectMake((kScreen_width-297)/2, 105, 297, 349);
    }
    
    [self.view addSubview:self.assignVC.view];
    [self addChildViewController:self.assignVC];
    
    //通知assignVC界面更新UI
    [[NSNotificationCenter defaultCenter] postNotificationName:@"assignVcRenewUiNotification" object:nil];
    
    //继续听警中
    [self getAlarmWithTimer];
    //结束定时器
    [self.countTimer setFireDate:[NSDate distantFuture]];
    //更改按钮的标题为听警中
    [self.goPoliceButton setTitle:@"听警中" forState:UIControlStateDisabled];
}

- (void)didDisposePolice {
    [self.goVC.view removeFromSuperview];
    [self.goVC removeFromParentViewController];
    
    [self.assignVC.view removeFromSuperview];
    [self.assignVC removeFromParentViewController];
    
    //执行跳动动画
    [self startAnimTimer];
    //继续听警中
    [self getAlarmWithTimer];
    //结束定时器
    [self.countTimer setFireDate:[NSDate distantFuture]];
    self.count = 10;
    //更改按钮的标题为听警中
    [self.goPoliceButton setTitle:@"听警中" forState:UIControlStateDisabled];
    
    [MBProgressHUD showSuccess:@"案情已处理" toView:self.view.window];
    
}

- (void)goHomeButtonEnable {
    //禁用出警按钮
    self.goPoliceButton.enabled = NO;
    [self.goPoliceButton setTitle:@"听警中" forState:UIControlStateDisabled];
    [self.goPoliceButton setTitleColor:HKColor(253, 151, 39) forState:UIControlStateDisabled];
    [self.goPoliceButton setBackgroundImage:[UIImage imageNamed:@"E1CF9B20-7D07-42FC-9994-5C8B2A4F5DDD.png"] forState:UIControlStateDisabled];
    //显示收工按钮
    self.goHomeButtom.hidden = NO;
    [self.assignVC.view removeFromSuperview];
    [self.assignVC removeFromParentViewController];
}

//发送通知，安全宝界面结束倒计时的Timer，取消听警
- (void)didGoPolice {
    [self.goVC.view removeFromSuperview];
    [self.goVC removeFromParentViewController];
    //结束定时器
    [self.countTimer setFireDate:[NSDate distantFuture]];
}

#pragma mark - actions
//出警按钮点击（出警）
- (IBAction)goPoliceButtonClicked:(id)sender {
    //播放动画
    [self startAnimTimer];
    
    NSString *status = [ReachabilityTool getReachability];
    HKLog(@"当前的网络状态是%@", status);
    if ([status isEqualToString:@"Not Reachable"]) {
        [MBProgressHUD showError:@"当前网络不可用" toView:self.view.window];
        return;
    }
    
    //修改状态为出警
    [self modifyPoliceState:@"2"];
    //重置计数器
    self.count = 10;
    //显示收工按钮
    self.goHomeButtom.hidden = NO;
    //禁用出警按钮
    self.goPoliceButton.enabled = NO;
    [self.goPoliceButton setTitle:@"听警中" forState:UIControlStateDisabled];
    [self.goPoliceButton setTitleColor:HKColor(253, 151, 39) forState:UIControlStateDisabled];
    [self.goPoliceButton setBackgroundImage:[UIImage imageNamed:@"E1CF9B20-7D07-42FC-9994-5C8B2A4F5DDD.png"] forState:UIControlStateDisabled];
    
    //轮询是否有案情
    [self getAlarmWithTimer];
}

//收工按钮点击（停警）
- (IBAction)goHomeButtonClicked:(id)sender {
    //停止跳动的动画
    [self.animTimer setFireDate:[NSDate distantFuture]];
    //停止轮询警情
    [self.alarmTimer setFireDate:[NSDate distantFuture]];
    //修改状态为停警
    [self modifyPoliceState:@"1"];
    //隐藏接警详情界面
    [self.goVC.view removeFromSuperview];
    [self.goVC removeFromParentViewController];
    
    //结束定时器
    [self.countTimer setFireDate:[NSDate distantFuture]];
    
    //隐藏收工按钮
    self.goHomeButtom.hidden = YES;
    //解除禁用出警按钮
    self.goPoliceButton.enabled = YES;
    
}


#pragma mark - 方法
//控制动画执行的timer
- (void)startAnimTimer {
    self.animTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(palyAnimation) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.animTimer forMode:NSRunLoopCommonModes];
    
}

//执行出警按钮跳动的动画
- (void)palyAnimation {
    [UIView animateWithDuration:1.0 animations:^{
        self.animImage.alpha = 0.0;
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:1.0 animations:^{
            self.animImage.alpha = 1.0;
        }];
    }];
}

- (void)getAlarmWithTimer {
    //初始化倒计时的时间，初始化轮询timer
    self.alarmTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(getAlarm) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.alarmTimer forMode:NSRunLoopCommonModes];
}

//开始计时器
- (void)startCountTimer {
    //初始化倒计时的时间，初始化倒计时timer
    self.countTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countFired) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.countTimer forMode:NSRunLoopCommonModes];
}

//计时器执行，count计数减1
- (void)countFired{
    self.count--;
    [self.goPoliceButton setTitle:[NSString stringWithFormat:@"%d", self.count] forState:UIControlStateDisabled];
    self.goPoliceButton.titleLabel.textAlignment = UIBaselineAdjustmentAlignCenters;
    if (self.count == 0) {
        //倒计时结束默认拒绝接警
        [self refuseAlarmWithAlarmId:alarmNum andPoliceId:policeNumber];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"alarmId"];
        //结束定时器
        [self.countTimer setFireDate:[NSDate distantFuture]];
        //更改按钮的标题为听警中
        [self.goPoliceButton setTitle:@"听警中" forState:UIControlStateDisabled];
        //继续听警中
        [self getAlarmWithTimer];
        //隐藏接警详情界面,并且弹出派给其他警员界面
        [self.goVC.view removeFromSuperview];
        [self.goVC removeFromParentViewController];
        
        self.assignVC = [[HKAssignPoliceViewController alloc] initWithNibName:@"HKAssignPoliceViewController" bundle:nil];
        if (kScreen_width == 320) {//5,5s,5SE
            self.assignVC.view.frame = CGRectMake((kScreen_width-240)/2, 80, 240, 300);
        }else {//6,6s,7
            self.assignVC.view.frame = CGRectMake((kScreen_width-297)/2, 105, 297, 349);
        }
        [self.view addSubview:self.assignVC.view];
        [self addChildViewController:self.assignVC];
        //通知assignVC界面更新UI
        [[NSNotificationCenter defaultCenter] postNotificationName:@"assignVcRenewUiNotification" object:nil];
        //计数器重置为10
        self.count = 10;
    }
}

//开始定位
- (void)startLocation{
    //初始化BMKLocationService
    self.locService = [[BMKLocationService alloc]init];
    self.locService.delegate = self;
    self.locService.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
    //启动LocationService
    [self.locService startUserLocationService];
}

#pragma mark - 网络请求

/**
 修改出警的状态
 @param state 1为停警，2为出警
 */
- (void)modifyPoliceState:(NSString *)state {
    NSURLSession *session = [NSURLSession sharedSession];
    NSString *urlString = [baseURL stringByAppendingString:@"mobile/police/modifyPoliceState/"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    request.HTTPMethod = @"POST";
    NSString *phoneStr = [NSString stringWithFormat:@"state=%@", state];//1表示停警，2表示出警
    NSString *msgStr = [NSString stringWithFormat:@"&policeId=%@", policeNumber];
    request.HTTPBody=[[phoneStr stringByAppendingString:msgStr] dataUsingEncoding:NSUTF8StringEncoding];
    NSURLSessionDataTask *task=[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
       
        if (error) {//如果出现网络问题直接返回
            return;
        }
        if (data == nil) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD showError:@"网络错误" toView:self.view];
                return;
            });
        }else {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
            NSLog(@"%@",[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
            if ([dict[@"meta"] isEqual: @"success"]) {//成功
                if([state isEqualToString:@"2"]) {
                    HKLog(@"修改状态为出警");
                }else {
                    HKLog(@"修改状态为停警");
                }
            }else {//失败
                if([state isEqualToString:@"2"]) {
                    HKLog(@"修改状态为停警");
                }else {
                    HKLog(@"修改状态为出警");
                }
            }
        }
    }];
    [task resume];
}

/**
 发送自己的位置
 @param policeId 警号
 @param longitude 经度
 @param latitude 纬度
 */
- (void)modifyPositionWithPoliceId:(NSString* )policeId andLongitude:(NSString *)longitude andLatitude:(NSString *)latitude {
    NSURLSession *session = [NSURLSession sharedSession];
    NSString *urlString = [baseURL stringByAppendingString:@"mobile/police/modifyPosition/"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    request.HTTPMethod = @"POST";
    NSString *policeNumStr = [NSString stringWithFormat:@"policeId=%@", policeId];//参数1：警号
    NSString *longitudeStr = [NSString stringWithFormat:@"&longitude=%@", longitude];//参数2：经度
    NSString *latitudeStr = [NSString stringWithFormat:@"&latitude=%@", latitude];//参数3：纬度
    //获取当前的时间
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
    NSString *dateTime = [formatter stringFromDate:[NSDate date]];
    
    HKLog(@"当前的时间是%@", dateTime);
    
    NSString *timeStr = [NSString stringWithFormat:@"&time=%@", dateTime];//参数4：当前的时间
    
    request.HTTPBody = [[[[policeNumStr stringByAppendingString:longitudeStr] stringByAppendingString:latitudeStr] stringByAppendingString:timeStr] dataUsingEncoding:NSUTF8StringEncoding];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {//如果出现网络错误，直接返回
            return;
        }
        NSLog(@"%@",[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
        if (data == nil) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD showError:@"网络错误" toView:self.view];
                return;
            });
        }else {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
            if ([dict[@"meta"] isEqual: @"success"]) {//发送实时位置成功
                HKLog(@"发送实时位置成功");
            }else {//发送实时位置失败
                dispatch_async(dispatch_get_main_queue(), ^{
                    [MBProgressHUD showError:@"发送实时位置失败" toView:self.view];
                });
            }
        }
    }];
    [task resume];
}

/**
 轮询是否有案件
 */
- (void)getAlarm {
    
    NSString *status = [ReachabilityTool getReachability];
    HKLog(@"当前的网络状态是%@", status);
    if ([status isEqualToString:@"Not Reachable"]) {
        [MBProgressHUD showError:@"当前网络不可用" toView:self.view.window];
        return;
    }else {
        NSURLSession *session = [NSURLSession sharedSession];
        NSString *urlString = [baseURL stringByAppendingString:@"mobile/police/getAlarm/"];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
        request.HTTPMethod = @"POST";
        NSString *msgStr = [NSString stringWithFormat:@"policeId=%@", policeNumber];
        request.HTTPBody=[msgStr dataUsingEncoding:NSUTF8StringEncoding];
        NSURLSessionDataTask *task=[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            if (error) {//如果出现网络错误，直接返回
                return;
            }
            if (data == nil) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [MBProgressHUD showError:@"网络错误" toView:self.view];
                    return;
                });
            }
            else {
                NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
                HKLog(@">>>>>>>>>>>>>%@", dict);
                if ([dict[@"meta"] isEqual: @"success"]) {//成功
                    HKLog(@"有案情");
                    


                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self.assignVC.view removeFromSuperview];
                        [self.assignVC removeFromParentViewController];
                        
                        //1.停止轮询警情,结束定时器
                        [self.alarmTimer setFireDate:[NSDate distantFuture]];
                        
                        HKLog(@"当前的经纬度是（%@， %@）",[[NSUserDefaults standardUserDefaults] objectForKey:@"currentLongitude"],  [[NSUserDefaults standardUserDefaults] objectForKey:@"currentLatitude"]);
                        HKLog(@"案件的经纬度是（%@， %@）",dict[@"alarmInfo"][@"longitude"], dict[@"alarmInfo"][@"latitude"]);
                        
                        //当前经纬度
                        double currentLongitude = [[[NSUserDefaults standardUserDefaults] objectForKey:@"currentLongitude"] doubleValue];
                        double currentLatitude = [[[NSUserDefaults standardUserDefaults] objectForKey:@"currentLatitude"] doubleValue];
                        //目的地经纬度
                        double longitude = [dict[@"alarmInfo"][@"longitude"] doubleValue];
                        double latitude = [dict[@"alarmInfo"][@"latitude"] doubleValue];
                        //距离
                        double distance = [self distanceBetweenOrderBy:currentLatitude :latitude :currentLongitude :longitude];
                        
                        
                        //2.保存案情相关的数据。
                        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
                        [userDefaults setObject:dict[@"alarmInfo"][@"address"] forKey:@"address"];
                        [userDefaults setObject:dict[@"alarmInfo"][@"alarmId"] forKey:@"alarmId"];
                        [userDefaults setObject:dict[@"alarmInfo"][@"latitude"] forKey:@"latitude"];
                        [userDefaults setObject:dict[@"alarmInfo"][@"longitude"] forKey:@"longitude"];
                        [userDefaults setDouble:distance forKey:@"distance"];
                        [userDefaults setObject:dict[@"alarmInfo"][@"poi"] forKey:@"poi"];
                        
                        //通知内容类
                        UNMutableNotificationContent *content = [UNMutableNotificationContent new];
                        //设置通知请求发送时 app图标上显示的数字
                        content.badge = @1;
                        //设置通知的内容
                        content.body = [NSString stringWithFormat:@"位置：%@，\n详情：%@，\n距离:%f",dict[@"alarmInfo"][@"address"], dict[@"alarmInfo"][@"poi"], distance];
                        //默认的通知提示音
                        content.sound = [UNNotificationSound defaultSound];
                        //设置通知的标题
                        content.title = @"出现新的警情，您是否接警前往？";
                        //设置从通知激活app时的launchImage图片
                        content.launchImageName = @"lun";
                        //设置5S之后执行
                        UNTimeIntervalNotificationTrigger * trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:0.1 repeats:NO];
                        UNNotificationRequest * request = [UNNotificationRequest requestWithIdentifier:@"NotificationDefault" content:content trigger:trigger];
                        //添加通知请求
                        [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
                            
                        }];
                        
                        //3.展示UI,显示接警详情界面
                        self.goVC = [[HKGoPoliceViewController alloc] initWithNibName:@"HKGoPoliceViewController" bundle:nil];
                        if (kScreen_width == 320) {//5,5s,5SE
                            self.goVC.view.frame = CGRectMake((kScreen_width-240)/2, 80, 240, 300);
                        }else {//6,6s,7
                            self.goVC.view.frame = CGRectMake((kScreen_width-297)/2, 105, 297, 349);
                        }
                        [self.view addSubview:self.goVC.view];
                        [self addChildViewController:self.goVC];
                        
                        //4.发送通知，接警详情界面更新UI
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"hasPoliceNotification" object:nil];
                        
                        //5.开启倒计时
                        [self startCountTimer];
                        //6.隐藏收工按钮
                        self.goHomeButtom.hidden = YES;
                        //0.播放音效
                        [HMAudioTool playAudioWithFilename:@"报警铃声.mp3"];
                        //震动
                        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
                        
                    });
                    
                }else {//失败
                    HKLog(@"没有案情");
                }
            }
        }];
        [task resume];
    }
    
    
}

/**
 拒绝接警
 @param alarmId 案件号
 @param policeId 警号
 */
- (void)refuseAlarmWithAlarmId:(NSString *)alarmId andPoliceId:(NSString *)policeId {
    NSURLSession *session = [NSURLSession sharedSession];
    NSString *urlString = [baseURL stringByAppendingString:@"mobile/police/refuseAlarm/"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    request.HTTPMethod = @"POST";
    NSString *alarmStr = [NSString stringWithFormat:@"alarmId=%@", alarmId];//参数1：案件编号
    NSString *policeStr = [NSString stringWithFormat:@"&policeId=%@", policeId];//参数2：警号
    
    request.HTTPBody = [[alarmStr stringByAppendingString:policeStr] dataUsingEncoding:NSUTF8StringEncoding];
    
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {//如果出现网络问题直接返回
            return;
        }
        if (data == nil) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD showError:@"网络错误" toView:self.view];
                return;
            });
        }else {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
            if ([dict[@"meta"] isEqual: @"success"]) {//拒绝接警成功
                NSLog(@"%@",[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
                HKLog(@"拒绝接警成功");
                dispatch_async(dispatch_get_main_queue(), ^{
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"refuseAlarmSuccessNotification" object:nil];
                });
            }else {//发送实时位置失败
                HKLog(@"拒绝接警失败");
                dispatch_async(dispatch_get_main_queue(), ^{
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"refuseAlarmFailNotification" object:nil];
                });

            }
        }
    }];
    [task resume];
}


/**
 获取崩溃状态

 @param policeId 警号
 */
- (void)getCrashStateWithPoliceId:(NSString *)policeId {
    NSURLSession *session = [NSURLSession sharedSession];
    NSString *urlString = [baseURL stringByAppendingString:@"mobile/police/initStatus"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    request.HTTPMethod = @"POST";
    NSString *policeStr = [NSString stringWithFormat:@"policeId=%@", policeId];//参数2：警号
    
    request.HTTPBody = [policeStr dataUsingEncoding:NSUTF8StringEncoding];
    
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data == nil) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD showError:@"网络错误" toView:self.view];
                return;
            });
        }else {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
            HKLog(@"%@", dict);
            if ([dict[@"state"] isEqual: @"2"]) {
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    HKLog(@"有没处理的案情");
                    
                    HKLog(@"当前的经纬度是（%@， %@）",[[NSUserDefaults standardUserDefaults] objectForKey:@"currentLongitude"],  [[NSUserDefaults standardUserDefaults] objectForKey:@"currentLatitude"]);
                    HKLog(@"案件的经纬度是（%@， %@）",dict[@"reservedAlarmInfo"][@"longitude"], dict[@"reservedAlarmInfo"][@"latitude"]);
                    //当前经纬度
                    double currentLongitude = [[[NSUserDefaults standardUserDefaults] objectForKey:@"currentLongitude"] doubleValue];
                    double currentLatitude = [[[NSUserDefaults standardUserDefaults] objectForKey:@"currentLatitude"] doubleValue];
                    //目的地经纬度
                    double longitude = [dict[@"reservedAlarmInfo"][@"longitude"] doubleValue];
                    double latitude = [dict[@"reservedAlarmInfo"][@"latitude"] doubleValue];
                    //距离
                    double distance = [self distanceBetweenOrderBy:currentLatitude :latitude :currentLongitude :longitude];
                    
                    //2.保存案情相关的数据。
                    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
                    [userDefaults setObject:dict[@"reservedAlarmInfo"][@"address"] forKey:@"address"];
                    [userDefaults setObject:dict[@"reservedAlarmInfo"][@"alarmId"] forKey:@"alarmId"];
                    [userDefaults setObject:dict[@"reservedAlarmInfo"][@"latitude"] forKey:@"latitude"];
                    [userDefaults setObject:dict[@"reservedAlarmInfo"][@"longitude"] forKey:@"longitude"];
                    [userDefaults setDouble:distance forKey:@"distance"];
                    [userDefaults setObject:dict[@"reservedAlarmInfo"][@"poi"] forKey:@"poi"];
                    [userDefaults setObject:dict[@"reservedAlarmInfo"][@"civilianTelephone"] forKey:@"civilianTel"];
                    
                    //展示处理警情界面
                    UIViewController *disposeVC = [[UIStoryboard storyboardWithName:@"Dispose" bundle:nil] instantiateInitialViewController];
                    [self presentViewController:disposeVC animated:YES completion:nil];
                    
                    //发送通知，处理警情界面更新UI
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"disposePoliceNotification" object:nil];
                    
                });
            }else if ([dict[@"state"] isEqual: @"1"]){
                dispatch_async(dispatch_get_main_queue(), ^{
                    HKLog(@"上次还在出警中");
                    //执行跳动动画
                    [self startAnimTimer];
                    //修改状态为出警
                    [self modifyPoliceState:@"2"];
                    //重置计数器
                    self.count = 10;
                    //显示收工按钮
                    self.goHomeButtom.hidden = NO;
                    //禁用出警按钮
                    self.goPoliceButton.enabled = NO;
                    [self.goPoliceButton setTitle:@"听警中" forState:UIControlStateDisabled];
                    [self.goPoliceButton setTitleColor:HKColor(253, 151, 39) forState:UIControlStateDisabled];
                    [self.goPoliceButton setBackgroundImage:[UIImage imageNamed:@"E1CF9B20-7D07-42FC-9994-5C8B2A4F5DDD.png"] forState:UIControlStateDisabled];
                    
                    //轮询是否有案情
                    [self getAlarmWithTimer];
                });
            }
        }
    }];
    [task resume];
}

#pragma mark - 监听位置改变的delegate
//处理位置坐标更新
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation {
    //每当修改代理方法的时候实时发送自己的位置
    NSString *longitudeStr = [NSString stringWithFormat:@"%f", userLocation.location.coordinate.longitude];
    NSString *latitudeStr = [NSString stringWithFormat:@"%f", userLocation.location.coordinate.latitude];
    
    //保存当前的经纬度
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:longitudeStr forKey:@"currentLongitude"];
    [userDefaults setObject:latitudeStr forKey:@"currentLatitude"];

    
    [self modifyPositionWithPoliceId:policeNumber andLongitude:longitudeStr andLatitude:latitudeStr];
    
}

//计算两点之间的距离
-(double)distanceBetweenOrderBy:(double) lat1 :(double) lat2 :(double) lng1 :(double) lng2{
    
    CLLocation *curLocation = [[CLLocation alloc] initWithLatitude:lat1 longitude:lng1];
    
    CLLocation *otherLocation = [[CLLocation alloc] initWithLatitude:lat2 longitude:lng2];
    
    double  distance  = [curLocation distanceFromLocation:otherLocation];
    
    return  distance;
    
}





@end
